package com.jesper.service;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    UserService userService;

    @Autowired
    HttpSession httpSession;

    @Autowired
    RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.jesper.model.User userDb = userService.getUserByName(username);

        if (userDb != null) {
            httpSession.setAttribute("user", userDb);
        } else {
            throw new UsernameNotFoundException("UsernameNotFoundException");
        }
        String password = userDb.getPassword();
        List<String> authList = roleService.getAut(userService.getRoleByName(username));//创建权限的集合，以List形式记录权限的字符串。
        System.out.println("当前账号具有的权限为:" + authList);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : authList) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
// 创建用户对象
        User user = new User("username", "password", authorities);
        return new User(username, password, authorities);
//        return new User(username, password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}
